<?php
class Workflow_m extends CI_Model{
	
	public $user_name = '';
	function __construct(){//重载父类的数据库连接方法
		parent::__construct();
		$this->load->helper('string');
		$this->user_name = $this->session->userdata('user_name');
		$this->user_id = $this->session->userdata('user_id');
		$this->dept_name = $this->session->userdata('dept_name');
		
	}
	
	//获取工作流列表
	function getlistdata($data){
		$this->db->from('flow_run');
 		$this->db->join('flow_run_ps', 'flow_run_ps.run_id = flow_run.run_id');
		$this->db->where('flow_run_ps.ps_username', $this->user_name); 

		if(array_key_exists("title",$data) || array_key_exists("atttitle",$data) || array_key_exists("sendname",$data) || array_key_exists("eids",$data) || array_key_exists("eide",$data)){
			if(array_key_exists("title",$data))
				$this->db->like('flow_run.run_title', $data['title']); 
			if(array_key_exists("atttitle",$data))
				$this->db->like('flow_run.attachment_name', $data['atttitle']); 
			if(array_key_exists("sendname",$data))
				$this->db->where_in('flow_run.begin_username',explode(",",reduce_multiples($data['sendname'],',',true)));
			if(array_key_exists("eids",$data))
				$this->db->where('flow_run.begin_datetime >=', $data['eids']);
			if(array_key_exists("eide",$data)){
				$eide = date('Y-m-d',strtotime($this->input->post('eide')." + 1 day"));
				$this->db->where('flow_run.begin_datetime <=', $eide);
			}
		}else{
			$this->db->where('flow_run_ps.ps_flag !=', '4');
		}
		$this->db->where('flow_run.del_flag', '0');
		
		$this->db->order_by($data['sort'], $data['order']); 
		$this->db->order_by("flow_run.run_id", 'desc'); 
		$start=($data['page']-1)*$data['rows'];
		$this->db->limit($data['rows'],$start);
		$query = $this->db->get();
		//echo $this->db->last_query();//输出随后一次查询的语
		return $query->result();
	}
	
	/*
	function workflow_all($searchParams = ''){
		//if($searchParams){
			$this->db->from('flow_run');
 			$this->db->join('flow_run_ps', 'flow_run_ps.run_id = flow_run.run_id');
			$this->db->where('flow_run_ps.ps_username', $this->user_name); 
			if($searchParams != ''){
				if(@$searchParams['title'])
					$this->db->like('flow_run.run_title', $searchParams['title']); 
				if(@$searchParams['atttitle'])
					$this->db->like('flow_run.attachment_name', $searchParams['atttitle']); 
				if(@$searchParams['sender'])
					$this->db->where_in('flow_run.begin_username',explode(",",$searchParams['sender']));
				if(@$searchParams['eids'])
					$this->db->where('flow_run.begin_datetime >=', $searchParams['eids']);
				if(@$searchParams['eide'])
					$this->db->where('flow_run.begin_datetime <=', $searchParams['eide']);
			}else{
				$this->db->where('flow_run_ps.ps_flag !=', '4');
			}
			$this->db->where('flow_run.del_flag', '0');	

			$query=$this->db->get();
			return $query->num_rows();

	}
	function workflow_limit($start,$end,$sort,$order,$searchParams = ''){		
		$this->db->select('*');
		$this->db->from('flow_run');
 		$this->db->join('flow_run_ps', 'flow_run_ps.run_id = flow_run.run_id');
		$this->db->where('flow_run_ps.ps_username', $this->user_name); 
		if($searchParams != ''){
			if(@$searchParams['title'])
				$this->db->like('flow_run.run_title', $searchParams['title']); 
			if(@$searchParams['atttitle'])
				$this->db->like('flow_run.attachment_name', $searchParams['atttitle']); 
			if(@$searchParams['sender'])
				$this->db->where_in('flow_run.begin_username',explode(",",$searchParams['sender']));
			if(@$searchParams['eids'])
				$this->db->where('flow_run.begin_datetime >=', $searchParams['eids']);
			if(@$searchParams['eide'])
				$this->db->where('flow_run.begin_datetime <=', $searchParams['eide']);
		}else{
			$this->db->where('flow_run_ps.ps_flag !=', '4');
		}
		
		$this->db->where('flow_run.del_flag', '0');
		
		$this->db->order_by("$sort", $order); 
		$this->db->order_by("flow_run.run_id", 'desc'); 
		$this->db->limit($end,$start);
		$query=$this->db->get();
		return $query->result();
	}
	*/

	function contentbox($id,$ps_id){
		$query = $this->db->where('run_id', $id)->where('ps_id', $ps_id)->where('ps_flag !=', 1)->limit(1)->get('flow_run_ps');
		if($query->num_rows() !== 1){
			//把上一个办理人的状态改为4，即已办结
			$this->db->update('flow_run_ps', array('ps_flag'=> '4'), array('run_id'=>$id,'ps_id'=>$ps_id-1));
			
			//把自己的状态改为2，即办理中，并添加上开始办理的时间
			$this->db->update('flow_run_ps', array('ps_datetime'=> date( "Y-m-d H:i:s", time()),'ps_flag'=> '2'), array('run_id'=>$id,'ps_id'=>$ps_id));
		}

		$sql = "SELECT * FROM yj_flow_run LEFT JOIN yj_flow_run_ps ON yj_flow_run.run_id = yj_flow_run_ps.run_id WHERE yj_flow_run.run_id = ? and yj_flow_run.del_flag = 0 and yj_flow_run_ps.ps_id = ? and yj_flow_run_ps.ps_username = ? limit 1";		
		$query = $this->db->query($sql, array($id,$ps_id,$this->user_name));
		return $query->result();
	}

	//新建工作流
	function workflow_add_post($data){
		//开始事务处理
		$this->db->trans_begin();
			$array = array(//工作流主体数据
				'run_id' => '', 
				'run_title' => $data['flow_add_title'], 
				'flow_id' => '1', 
				'begin_username' => $this->user_name,
				'begin_dept' => $this->dept_name, 
				'begin_datetime'=> date("Y-m-d H:i:s",time()),
				'end_datetime'=> '0000-00-00 00:00:00',
				'attachment_id'=> '',
				'attachment_name'=> '',				
				'size'=> '',
				'del_flag'=>'0'
			);
			$this->db->set($array);
			$this->db->insert('flow_run'); //插入工作流主体
			$run_id = $this->db->insert_id();

			$array = array(//办理人数据
				'id' => '',
				'run_id' => $run_id,
				'ps_id' => '1',
				'ps_dept' => $this->dept_name,
				'ps_username' => $this->user_name,
				'ps_datetime' => date("Y-m-d H:i:s",time()),
				'deliver_datetime' => '',
				'create_datetime' => date("Y-m-d H:i:s",time()),
				'ps_flag' => '2'				
			);
			$this->db->set($array);
			$this->db->insert('flow_run_ps'); //插入办理人数组
		
		if($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();//事件回滚	
			return false;		
		}else{
			$this->db->trans_commit();//提交成功
			return $run_id;
		}//事务结束
	}
	
	function get_workflow_row_data($run_id,$str){
		$this->db->select($str);
		$this->db->from('flow_run');
 		$this->db->join('flow_run_ps', 'flow_run_ps.run_id = flow_run.run_id');
		$this->db->where('flow_run_ps.ps_username', $this->user_name); 
		$this->db->where('flow_run.run_id', $run_id); 
		$query=$this->db->get();
		return $query->first_row();
	}
	
	/*-上传文件-*/
	function upfile(){
		$json = $this->input->post('data');
		$run_id = $this->input->post('id');
		$filearr = json_decode($json,true);	
		
		$attdaterand = '';
		$attnames = '';
		$attsize = '';
		
		$rowdata = $this->get_workflow_row_data($run_id,'attachment_id,attachment_name,size');
		$attdaterand = $rowdata->attachment_id;
		$attnames = $rowdata->attachment_name;
		$attsize = $rowdata->size;

		for($i=0; $i<count($filearr); $i++){
			$attdaterand .= $filearr[$i]['daterand'].',';
			$attnames .= $filearr[$i]['name'].'*';
			$attsize .= $filearr[$i]['size'].',';//所有附件的和
		}
		
		$array = array(
			'attachment_id'=> $attdaterand,
			'attachment_name'=> $attnames,
			'size'=> $attsize
		);
		$this->db->where('run_id', $run_id);
		return $this->db->update('flow_run',$array); //插入更新附件信息
		
	}
	/*
	function str_replace_limit($search, $replace, $subject, $limit=-1) { 
		// constructing mask(s)... 
		if (is_array($search)){ 
			foreach ($search as $k=>$v) { 
				$search[$k] = '`' . preg_quote($search[$k],'`') . '`'; 
			}
		}else{ 
			$search = '`' . preg_quote($search,'`') . '`'; 
		} 
		// replacement 
		return preg_replace($search, $replace, $subject, $limit); 
	} 
	*/
	
	function del_att($data){
		$rowdata = $this->get_workflow_row_data($data['run_id'],'attachment_id,attachment_name,size');
		
		$attdaterand = explode(',',reduce_multiples($rowdata->attachment_id,',',true));
		$attnames = explode('*',reduce_multiples($rowdata->attachment_name,'*',true));  //文件名分隔符是*号
		$attsizes = explode(',',reduce_multiples($rowdata->size,',',true));  //文件名分隔符是*号
		
		$founded = array_search($data['att_id'], $attdaterand);  

		unset($attdaterand[$founded]); 
		unset($attnames[$founded]);
		unset($attsizes[$founded]); 
		
		if(empty($attdaterand) || empty($attnames) || empty($attsizes)){//如果删除最后一个附件后ID或文件名任意一个为空，则视为全部为空
			$attdaterand = '';
			$attnames = '';
			$attsizes = '';
		}else{
			$attdaterand=implode(",",$attdaterand).',';
			$attnames=implode("*",$attnames).'*';
			$attsizes=implode(",",$attsizes).',';
		}
		
		//$attdaterand = $this->str_replace_limit($data['att_id'].',', '', $rowdata->attachment_id,1);
		//$attnames = $this->str_replace_limit($data['att_name'].'*', '', $rowdata->attachment_name,1);
		
		//if($attdaterand == '' || $attnames == ''){//如果删除最后一个附件后ID或文件名任意一个为空，则视为全部为空
			
		//}
		
		$array = array(
			'attachment_id'=> $attdaterand,
			'attachment_name'=> $attnames,
			'size'=> $attsizes
		);

		$this->db->where('run_id', $data['run_id']);
		return $this->db->update('flow_run',$array); //插入更新附件信息
		
	}
	
	//转交下一步POST方法
	function next_handed_post($data){
		//开始事务处理
		$this->db->trans_begin();
			$array = array(
				'deliver_datetime'=> date( "Y-m-d H:i:s", time()),
				'ps_flag'=> '3'
			);
			$this->db->where('run_id', $data['run_id']);
			$this->db->where('ps_id', $data['ps_id']);
			$this->db->update('flow_run_ps',$array); 
			
			$array = array(//下一步办理人数据
				'id' => '',
				'run_id' => $data['run_id'],
				'ps_id' => $data['ps_id']+1,
				'ps_dept' => '',
				'ps_username' => $data['ps_username'],
				'ps_datetime' => '',
				'deliver_datetime' => '',
				'create_datetime' => date( "Y-m-d H:i:s", time()),
				'ps_flag' => '1'
			);
			$this->db->set($array);
			$this->db->insert('flow_run_ps');
			
			//短信提醒
			$smsarr = array(
                'bodyid' => '' ,
                'sender' => $this->user_name,
                'smstype' => '4',
				'alerttype' => '0',
				'content' => $this->user_name.'向您转办了一项工作：'.$data['run_title'],
				'sendtime' => date("Y-m-d H:i:s",time()),
				'remindurl' => 'workflow/index/'
             ); 
			$this->db->insert('sms_body', $smsarr); //插入短信提醒主体数据
			$bodyid = $this->db->insert_id();
			
			$arr = array(//短信收信人数据
				'smsid' => '',
				'to_id' => $data['ps_userid'],
				'to_name' => $data['ps_username'],
				'sms_read' => '0',
				'readtime' => date("Y-m-d H:i:s",time()),
				'sms_delete' => '0',
				'bodyid' => $bodyid
			);
			$this->db->insert('sms',$arr); //插入接收邮件数组
			
		if($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();//事件回滚	
			return false;		
		}else{
			$this->db->trans_commit();//提交成功
			return true;
		}//事务结束
	}
	
	//流程图
	function workflow_flowchart($run_id,$num = 0){
		$this->db->where('run_id', $run_id);
		$this->db->order_by('flow_run_ps.ps_id', 'asc'); 
		$query=$this->db->get('flow_run_ps');
		if($num == 1){
			return $query->num_rows();
		}else{
			return $query->result();
		}
	}
	
	//结束流程
	function workflow_flow_end($data){
		$array = array(
			'deliver_datetime'=> date( "Y-m-d H:i:s", time()),
			'ps_flag'=> '4'
		);
		$this->db->where('run_id', $data['run_id']);
		$this->db->where('ps_id', $data['ps_id']);
		return $this->db->update('flow_run_ps',$array); 
	}
	
	//删除流程
	function workflow_flow_del($data){
		$tables = array('flow_run','flow_run_ps');
		$this->db->where('run_id',$data['run_id']);
		$this->db->delete($tables);
		return true;
	}
	
	//收回流程
	function workflow_flow_back($data){
		//开始事务处理
		$this->db->trans_begin();
			$this->db->delete('flow_run_ps', array('run_id' => $data['run_id'],'ps_id' => $data['ps_id']+1)); 
			$array = array(
				'deliver_datetime'=> '0000-00-00 00:00:00',
				'ps_flag'=> '2'
			);
			$this->db->where('run_id', $data['run_id']);
			$this->db->where('ps_id', $data['ps_id']);
			$this->db->update('flow_run_ps',$array); 
		if($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();//事件回滚	
			return false;		
		}else{
			$this->db->trans_commit();//提交成功
			return true;
		}//事务结束
	}
}
?>